<template>
  <div class="deposit-report">
    <!-- 统计指标区域 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="deposit-stat-card">
          <div class="deposit-stat">
            <div class="stat-title">总保证金
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 480px; line-height: 1.5;">
                  <div><strong>定义：</strong>查询时间范围内的保证金充值总额（非当前余额）</div>
                  <div><strong>计算：</strong>SUM(充值金额)</div>
                  <div><strong>来源：</strong><code>consul_nfc_deposit_record</code>（record_type=DEPOSIT）</div>
                  <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                  <div style="margin-top: 8px; padding: 8px; background: #2c3e50; border-radius: 4px; color: #fff;">
                    <div><strong>💡 实例说明：</strong></div>
                    <div>张记小吃在3月份：</div>
                    <div>• 1号充值：1000元</div>
                    <div>• 15号充值：500元</div>
                    <div>• 30号充值：300元</div>
                    <div><strong>总保证金 = 1800元</strong>（历史累计充值）</div>
                    <div style="color: #bdc3c7; font-size: 12px;">注：即使期间有消费或冻结，总保证金仍为1800元</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
              </el-tooltip>
            </div>
            <div class="stat-amount">¥{{ depositData.total_deposit || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="deposit-stat-card">
          <div class="deposit-stat">
            <div class="stat-title">可用保证金
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 480px; line-height: 1.5;">
                  <div><strong>定义：</strong>期末时点"可用余额"</div>
                  <div><strong>计算：</strong>期初可用余额 + ∑(充值 + 解冻 − 退款 − 冻结) 截止结束日期</div>
                  <div><strong>来源：</strong><code>consul_nfc_deposit_record</code> 按类型累计</div>
                  <div style="margin-top: 8px; padding: 8px; background: #34495e; border-radius: 4px; color: #fff;">
                    <div><strong>💡 银行账户类比：</strong></div>
                    <div>就像银行活期存款，可用保证金是"现在能花的钱"</div>
                    <div style="margin-top: 6px;"><strong>张记小吃的账户：</strong></div>
                    <div>• 月初余额：800元</div>
                    <div>• 本月充值：500元</div>
                    <div>• 订单冻结：200元</div>
                    <div>• 解冻回来：50元</div>
                    <div><strong>可用保证金 = 1150元</strong>（当前能用的钱）</div>
                    <div style="color: #bdc3c7; font-size: 12px;">注：这是当前可以立即使用的余额</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
              </el-tooltip>
            </div>
            <div class="stat-amount available">¥{{ depositData.available_deposit || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="deposit-stat-card">
          <div class="deposit-stat">
            <div class="stat-title">冻结保证金
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 480px; line-height: 1.5;">
                  <div><strong>定义：</strong>期末时点"冻结中的余额"</div>
                  <div><strong>计算：</strong>∑(冻结) − ∑(解冻) 截止结束日期</div>
                  <div><strong>来源：</strong><code>consul_nfc_deposit_record</code> 按类型累计</div>
                  <div style="margin-top: 8px; padding: 8px; background: #e67e22; border-radius: 4px; color: #fff;">
                    <div><strong>💡 业务场景说明：</strong></div>
                    <div>冻结保证金就像"临时锁定的钱"，常见场景：</div>
                    <div style="margin-top: 6px;"><strong>张记小吃的情况：</strong></div>
                    <div>• 接单时冻结：100元（确保有钱付配送费）</div>
                    <div>• 投诉处理冻结：50元（等待调查结果）</div>
                    <div>• 违约金冻结：30元（处理纠纷期间）</div>
                    <div><strong>冻结保证金 = 180元</strong>（暂时不能用的钱）</div>
                    <div style="color: #ecf0f1; font-size: 12px;">注：订单完成或问题解决后会自动解冻</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
              </el-tooltip>
            </div>
            <div class="stat-amount frozen">¥{{ depositData.frozen_deposit || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="deposit-stat-card">
          <div class="deposit-stat">
            <div class="stat-title">保证金使用率
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 480px; line-height: 1.5;">
                  <div><strong>定义：</strong>已使用金额 / 总充值金额 × 100%</div>
                  <div><strong>已使用金额：</strong>∑(充值) − ∑(退款) − 当前账户总余额</div>
                  <div><strong>当前账户总余额：</strong>可用保证金 + 冻结保证金（期末时点）</div>
                  <div style="margin-top: 8px; padding: 8px; background: #27ae60; border-radius: 4px; color: #fff;">
                    <div><strong>💡 简单理解：</strong></div>
                    <div>保证金使用率 = <strong>已经花掉的钱 ÷ 总共充值的钱</strong></div>
                    <div style="margin-top: 6px;"><strong>张记小吃的例子：</strong></div>
                    <div>• 总共充值：2000元</div>
                    <div>• 当前账户余额：1330元（可用1150+冻结180）</div>
                    <div>• 已使用金额：2000 - 1330 = 670元</div>
                    <div><strong>使用率 = 670 ÷ 2000 = 33.5%</strong></div>
                    <div style="color: #ecf0f1; font-size: 12px;">注：使用率高说明资金周转活跃，使用率低说明资金沉淀较多</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
              </el-tooltip>
            </div>
            <div class="stat-amount">{{ depositData.usage_rate || 0 }}%</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card>
          <div slot="header">保证金变动趋势
            <el-tooltip placement="top">
              <div slot="content" style="max-width: 520px; line-height: 1.5;">
                <div><strong>定义：</strong>展示每日"金额变动"，非余额曲线；另含"可用余额（累计）"曲线</div>
                <div><strong>三条曲线口径（变动）：</strong></div>
                <div>• 净流入（total_trend）= 充值(Deposit) − 退款(Refund)</div>
                <div>• 可用变动（available_trend）= 充值 + 解冻 − 退款 − 冻结</div>
                <div>• 冻结变动（frozen_trend）= 冻结 − 解冻</div>
                <div><strong>累计口径：</strong>可用余额（累计）= 期初可用余额 + ∑(可用变动)</div>
                <div><strong>期初口径：</strong>期初可用余额 = 统计起始日前累计(充值 + 解冻 − 退款 − 冻结)</div>
                <div><strong>来源：</strong><code>consul_nfc_deposit_record</code> 按天+类型聚合（仅统计有效记录）</div>
                <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                <div><strong>提示：</strong>如需仅看余额，请关注"可用余额（累计）"虚线；其余为每日变动值</div>
              </div>
              <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
            </el-tooltip>
            <el-popover placement="top" trigger="click" width="520">
              <div style="line-height:1.6;">
                <div><strong>小白课堂（直白结论）：</strong> 当天的4条线，都是把这一天的流水按类型加总后，做个简单加减法，最后保留两位小数（单位：元）。</div>
                <div style="margin-top:6px;"><strong>你只需要知道当天四个数：</strong></div>
                <div>• 当天充值合计 = 当天所有充值金额之和</div>
                <div>• 当天退款合计 = 当天所有退款金额之和</div>
                <div>• 当天冻结合计 = 当天所有冻结金额之和</div>
                <div>• 当天解冻合计 = 当天所有解冻金额之和</div>
                <div style="margin-top:6px;"><strong>然后公式就是：</strong></div>
                <div>• 净流入 = 当天充值合计 − 当天退款合计</div>
                <div>• 可用变动 = 当天充值合计 + 当天解冻合计 − 当天退款合计 − 当天冻结合计</div>
                <div>• 冻结变动 = 当天冻结合计 − 当天解冻合计</div>
                <div>• 可用余额（累计）= 昨天的可用余额（累计）+ 今天的可用变动</div>
                <div style="margin-top:6px; color:#666;">
                  <div>• Tooltip 上的每个值，都是用上面这四条公式算出来的</div>
                </div>
              </div>
              <el-button slot="reference" type="text" style="margin-left:10px;">小白课堂</el-button>
            </el-popover>
          </div>
          <div id="depositTrendChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { nfcReportsAPI } from '@/api/nfc'
import * as echarts from 'echarts'

export default {
  name: 'DepositReport',
  props: {
    filters: { type: Object, required: true }
  },
  data() {
    return {
      loading: false,
      depositData: {},
      chartInstances: {},
      chartResizeObservers: {}
    }
  },
  watch: {
    filters: { handler() { this.loadData() }, deep: true }
  },
  mounted() {
    this.loadData()
  },
  beforeDestroy() {
    // 清理图表实例
    Object.values(this.chartInstances).forEach(chart => chart && chart.dispose())
    // 清理尺寸监听器
    Object.values(this.chartResizeObservers).forEach(observer => {
      try {
        observer.disconnect()
      } catch (e) {
        console.warn('断开图表尺寸监听器失败:', e)
      }
    })
  },
  methods: {
    async loadData() {
      try {
        this.loading = true
        const response = await nfcReportsAPI.getDepositReport(this.filters)
        const raw = response.data || {}
        const ov = raw.overview || {}
        
        // 复杂的业务计算逻辑
        const totalPaid = parseFloat(ov.total_paid || 0) || 0
        const totalRefunded = parseFloat(ov.total_refunded || 0) || 0
        const totalBalance = parseFloat(ov.total_balance || 0) || 0
        const totalFrozen = parseFloat(ov.total_frozen || 0) || 0
        const availableBalance = parseFloat(ov.available_balance || 0) || 0
        const used = Math.max(0, totalPaid - totalRefunded - totalBalance)
        const usageRate = totalPaid > 0 ? ((used / totalPaid) * 100).toFixed(2) : '0.00'
        
        // 构建完整的保证金数据
        this.depositData = {
          total_deposit: totalPaid,
          available_deposit: availableBalance,
          frozen_deposit: totalFrozen,
          usage_rate: usageRate,
          // 图表数据
          trend_dates: raw.trend_dates || [],
          total_trend: raw.total_trend || [],
          available_trend: raw.available_trend || [],
          frozen_trend: raw.frozen_trend || [],
          available_balance_trend: raw.available_balance_trend || []
        }
        
        this.$nextTick(() => {
          this.renderDepositCharts(this.depositData)
        })
      } catch (error) {
        console.error('加载保证金数据失败：', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    // 渲染保证金图表
    renderDepositCharts(data) {
      this.renderChart('depositTrendChart', {
        title: { text: '' },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            if (!Array.isArray(params)) params = [params]
            const date = params[0] && (params[0].axisValue || params[0].name) || ''
            const lines = [date]
            params.forEach(p => {
              const val = (typeof p.data === 'number') ? p.data : Number(p.data || 0)
              lines.push(`${p.marker}${p.seriesName}：¥${val.toFixed(2)}`)
            })
            // 与标题Tooltip一致的口径文案（含字段名）
            lines.push('<span style="color:#909399">变动口径：净流入=充值-退款；可用变动=充值+解冻-退款-冻结；冻结变动=冻结-解冻</span>')
            lines.push('<span style="color:#909399">累计口径：可用余额（累计）= 期初可用余额 + ∑(可用变动)</span>')
            lines.push('<span style="color:#909399">字段：total_trend / available_trend / frozen_trend / available_balance_trend</span>')
            return lines.join('<br/>')
          }
        },
        legend: {
          data: ['净流入（total_trend）', '可用变动（available_trend）', '冻结变动（frozen_trend）', '可用余额（累计）']
        },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', name: '日期', data: data.trend_dates || [] },
        yAxis: { type: 'value', name: '金额（元）', axisLabel: { formatter: (v) => `¥${v}` } },
        series: [
          {
            name: '净流入（total_trend）',
            type: 'line',
            data: data.total_trend || [],
            itemStyle: { color: '#409EFF' },
            smooth: true
          },
          {
            name: '可用变动（available_trend）',
            type: 'line',
            data: data.available_trend || [],
            itemStyle: { color: '#67C23A' },
            smooth: true
          },
          {
            name: '冻结变动（frozen_trend）',
            type: 'line',
            data: data.frozen_trend || [],
            itemStyle: { color: '#F56C6C' },
            smooth: true
          },
          {
            name: '可用余额（累计）',
            type: 'line',
            data: data.available_balance_trend || [],
            itemStyle: { color: '#E6A23C' },
            lineStyle: { type: 'dashed' },
            smooth: true
          }
        ]
      })
    },
    
    // 通用图表渲染方法（带 ResizeObserver 与首帧自适应）
    renderChart(containerId, option) {
      const container = document.getElementById(containerId)
      if (!container) return
      
      // 清理旧实例与观察器
      if (this.chartInstances[containerId]) {
        this.chartInstances[containerId].dispose()
        this.chartInstances[containerId] = null
      }
      if (this.chartResizeObservers[containerId]) {
        try {
          this.chartResizeObservers[containerId].disconnect()
        } catch (e) {
          console.warn('断开图表尺寸监听器失败:', e)
        }
        delete this.chartResizeObservers[containerId]
      }
      
      // 初始化图表
      const chart = echarts.init(container)
      chart.setOption(option)
      this.chartInstances[containerId] = chart
      
      // 添加 ResizeObserver 监听容器尺寸变化
      if (window.ResizeObserver) {
        const observer = new ResizeObserver(() => {
          try {
            chart.resize()
          } catch (e) {
            console.warn('图表自适应失败:', e)
          }
        })
        observer.observe(container)
        this.chartResizeObservers[containerId] = observer
      }
      
      // 防抖处理窗口 resize 事件
      const handleResize = () => {
        clearTimeout(this.resizeTimer)
        this.resizeTimer = setTimeout(() => {
          try {
            chart.resize()
          } catch (e) {
            console.warn('窗口 resize 图表适配失败:', e)
          }
        }, 100)
      }
      window.addEventListener('resize', handleResize)
    }
  }
}
</script>

<style scoped>
.deposit-report {
  padding: 0;
}

/* 保证金统计卡片样式 */
.deposit-stat-card {
  text-align: center;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.deposit-stat-card .el-card__body {
  padding: 0;
  height: 120px;
}

.deposit-stat {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.2;
}

/* 颜色区分 */
.stat-amount.available {
  color: #67C23A; /* 可用保证金 - 绿色 */
}

.stat-amount.frozen {
  color: #F56C6C; /* 冻结保证金 - 红色 */
}

/* 图表区域样式 */
.chart-row {
  margin-top: 20px;
}

.chart-row .el-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.chart-row .el-card__header {
  background-color: #F5F7FA;
  border-bottom: 1px solid #EBEEF5;
  padding: 18px 20px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
}

.chart-row .el-card__body {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .deposit-stat {
    padding: 15px 10px;
  }
  
  .stat-title {
    font-size: 12px;
  }
  
  .stat-amount {
    font-size: 20px;
  }
  
  .chart-row .el-card__body {
    padding: 15px;
  }
}
</style>